<template>
  <div class="forum-post" :class="{ 'sticky-post': post.isSticky, 'essence-post': post.isEssence }">
    <div>
    </div>
    <div class="post-header">
      <div class="post-author">
        <img :src="post.user ? (post.user.avatar ? 'http://localhost:8081' + post.user.avatar : defaultAvatar) : defaultAvatar" 
         alt="作者头像" class="author-avatar">
        <span class="author-nickname">{{ post.user ? post.user.username : '未知用户' }}</span>
        <span class="post-date">{{ new Date(post.date).toLocaleString() }}</span>
      </div>
      
      <div class="post-badges">
        <span v-if="post.isSticky" class="sticky-mark">置顶</span>
        <span v-if="post.isEssence" class="essence-mark">精华</span>
        <div v-if="isAdmin" class="admin-actions">
          <el-tooltip content="置顶" placement="top">
            <el-button 
              @click.stop="$emit('toggle-sticky', post)"
              :type="post.isSticky ? 'success' : ''"
              size="mini"
              icon="el-icon-top"
              circle
            ></el-button>
          </el-tooltip>
          <el-tooltip content="精华" placement="top">
            <el-button 
              @click.stop="$emit('toggle-essence', post)"
              :type="post.isEssence ? 'warning' : ''"
              size="mini"
              icon="el-icon-star-on"
              circle
            ></el-button>
          </el-tooltip>
        </div>
      </div>
    </div>
    
    <h3>{{ post.title }}</h3>
    <p>{{ post.content }}</p>
    
    <!-- 显示上传的图片 -->
    <div v-if="post.images && post.images.length > 0">
      <img v-for="(image, imgIndex) in post.images" :key="imgIndex" :src="image.url" alt="" style="max-width: 100%; margin-top: 10px;">
    </div>
    
    <div class="post-actions">
      <el-button type="text" @click="likePost(post)">
        <i class="el-icon-thumbs-up"></i> 点赞 ({{ post.likes }})
      </el-button>
      <el-button type="text" @click="toggleCommentInput(post)">
        <i class="el-icon-chat-line-round"></i> 评论 ({{ post.replies }})
      </el-button>
      <el-button type="text" @click="toggleFavorite(post)">
        <i class="el-icon-star-on"></i>
        {{ post.isCollected ? '取消收藏' : '收藏' }}
      </el-button>
      
      <!-- 编辑和删除按钮 -->
      <el-button 
    type="text" 
    v-if="post.user && post.user.username === currentUsername"
    @click="editPost(post)"
    style="color: #409eff;"
  >
    <i class="el-icon-edit"></i> 编辑
  </el-button>
      <el-button 
      type="text" 
      v-if="post.user && post.user.username === currentUsername"
      @click="deletePost(post)"
      style="color: #f56c6c;"
    >
      <i class="el-icon-delete"></i> 删除
    </el-button>
    </div>
    
    <!-- 评论区 -->
    <div class="comments-section">
      <h4>评论区</h4>
      <div class="comment-input">
        <el-input
          type="textarea"
          v-model="newComment"
          placeholder="写下你的评论..."
          maxlength="255"
          show-word-limit
        ></el-input>
        <el-button type="primary" @click="submitComment" style="width: 150px; align-self:center">发布评论</el-button>
      </div>
      <div class="comments-list">
        <div v-for="(comment, index) in comments" :key="index" class="comment-item">
          <div class="comment-header">
            <span class="comment-user">{{ comment.user ? comment.user.username : '未知用户' }}</span>
            <span class="comment-time">{{ formatTime(comment.createdAt) }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>

          <!-- 回复功能 -->
          <div class="reply-input">
            <el-input
              v-if="showReplyInput === comment.id"
              type="textarea"
              v-model="newReply[comment.id]"
              placeholder="回复此评论..."
              maxlength="255"
              show-word-limit
            ></el-input>
            <el-button
              v-if="showReplyInput === comment.id"
              type="primary"
              @click="submitReply(comment.id)"
            >发送回复</el-button>
            <el-button
              v-else
              type="text"
              @click="toggleReplyInput(comment.id)"
            >回复</el-button>
          </div>
          <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
            <div v-for="(reply, replyIndex) in comment.replies" :key="replyIndex" class="reply-item">
              <div class="reply-header">
                <span class="reply-user">{{ reply.user ? reply.user.username : '未知用户' }}</span>
                <span class="reply-time">{{ formatTime(reply.createdAt) }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="post.images && post.images.length > 0">
      <img v-for="(image, imgIndex) in post.images" :key="imgIndex" :src="image.url" alt="" style="max-width: 100%; margin-top: 10px;">
    </div>
  </div>
</template>

<script>
import api from '@/api/api'; 
import { mapGetters, mapActions } from 'vuex';

export default {
  data() {
    return {
      defaultAvatar: 'src\assets\logo1.png',
      newComment: '',
      comments: [],
      showReplyInput: null,
      newReply: {}
    };
  },
  props: {
    post: {
      type: Object,
      required: true,
      validator: (post) => {
        return post && typeof post === 'object' && post.hasOwnProperty('id');
      }
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    this.fetchComments();
    this.fetchReplies();
  },

  computed: {
    ...mapGetters(['isPostCollected']),
  isCollected() {
    return this.isPostCollected(this.post.id);},
    ...mapGetters(['getUsername', 'getAvatar', 'isPostCollected']),
    currentUsername() {
      return this.$store.getters.getUsername;
    },
    currentAvatar() {
      return this.$store.getters.getAvatar;
    }
  },
  methods: {
    ...mapActions(['addFavorite', 'removeFavorite', 'fetchFavorites']),

    toggleFavorite(post) {
    post.isCollected = !post.isCollected;
    const username = this.$store.state.username;
    console.log('Current username from store:', username);
    if (post.isCollected) {
      api.addFavorite(username, post.id)
        .then(response => {
          this.$message.success('收藏成功');
        })
        .catch(error => {
          console.error('收藏失败:', error);
          this.$message.error('收藏失败，请稍后再试');
        });
    } else {
      api.removeFavorite(username, post.id)
        .then(response => {
          this.$message.success('已取消收藏');
        })
        .catch(error => {
          console.error('取消收藏失败:', error);
          this.$message.error('取消收藏失败，请稍后再试');
        });
    }
  },

    editPost(post) {
      this.$emit('edit-post', post); // 触发 edit-post 事件
    },
    formatTime(timeString) {
      if (!timeString) return '';
      return timeString.split('.')[0].replace('T', ' ');
    },
    likePost(post) {
      this.$emit('like-post', post);
      api.likePost(post.id)
          .then(response => {
              post.likes = response.data.likes;
              this.$message.success('点赞成功');
          })
          .catch(error => {
              console.error('点赞失败:', error);
              this.$message.error('点赞失败，请稍后再试');
          });
    },
    toggleCommentInput(post) {
      this.$emit('toggle-comment-input', post);
      post.showCommentInput = !post.showCommentInput;
    },
    collectPost(post) {
      this.$emit('collect-post', post);
      const index = this.collectedPosts.findIndex(p => p.id === post.id);
      if (index === -1) {
        this.collectedPosts.push({ ...post, isCollected: true });
        post.isCollected = true;
        this.$message.success('收藏成功');
      } else {
        this.collectedPosts.splice(index, 1);
        post.isCollected = false;
        this.$message.success('已取消收藏');
      }
    },

    deletePost(post) {
  api.deletePost(post.id)
    .then(response => {
      this.$message.success('删除成功');
      this.$emit('post-deleted', post.id);
    })
    .catch(error => {
      console.error('删除失败:', error);
      this.$message.error('删除失败，请稍后再试');
    });
},
    fetchComments() {
      if (!this.post.id || isNaN(this.post.id)) {
        console.error('postId 不合法:', this.post.id);
        return;
      }
      api.getComments(this.post.id)
        .then(response => {
          this.comments = response.data;
        })
        .catch(error => {
          console.error('获取评论失败:', error);
        });
    },
    fetchReplies() {
      this.comments.forEach(comment => {
        api.getRepliesByCommentId(comment.id)
          .then(response => {
            this.comments.find(c => c.id === comment.id).replies = response.data;
          })
          .catch(error => {
            console.error('获取回复失败:', error);
          });
      });
    },
    submitComment() {
      if (!this.newComment.trim()) {
        this.$message.error('评论内容不能为空');
        return;
      }

      const commentData = {
        content: this.newComment
      };

      api.createComment(this.post.id, commentData)
        .then(response => {
          this.comments.unshift(response.data);
          this.newComment = '';
        })
        .catch(error => {
          console.error('发布评论失败:', error);
          this.$message.error('发布评论失败，请稍后再试');
        });
    },
    toggleReplyInput(commentId) {
      this.showReplyInput = this.showReplyInput === commentId ? null : commentId;
    },
    submitReply(commentId) {
      if (!this.newReply[commentId] || !this.newReply[commentId].trim()) {
        this.$message.error('回复内容不能为空');
        return;
      }

      const replyData = {
        content: this.newReply[commentId]
      };

      api.createReply(commentId, replyData)
        .then(response => {
          const comment = this.comments.find(comment => comment.id === commentId);
          if (comment) {
            if (!comment.replies) {
              this.$set(comment, 'replies', []);
            }
            comment.replies.unshift(response.data);
          }
          this.newReply[commentId] = '';
          this.showReplyInput = null;
        })
        .catch(error => {
          console.error('发布回复失败:', error);
          this.$message.error('发布回复失败，请稍后再试');
        });
    },
  }
};
</script>

<style scoped>
.forum-post {
  position: relative;
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.post-header {
  display: flex;
  justify-content: space-between;
  position: relative;
  padding-right: 140px;
}
.post-badges {
  position: absolute;
  right: 15px;
  top: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10px;
}

.sticky-post, .essence-post {
    background-color: transparent; 
    border: none; 
}

.sticky-mark, .essence-mark {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  color: white;
  margin-right: auto;
  margin-top:30px;
}

.admin-actions {
  display: flex;
  gap: 8px;
}
/* 响应式调整 */
@media (max-width: 768px) {
  .post-header {
    padding-right: 120px;
  }
  .post-badges {
    flex-direction: column;
    align-items: flex-end;
  }
}

.post-author {
  display: flex;
  align-items: center;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.author-nickname {
  font-weight: bold;
  margin-right: 10px;
}

.post-date {
  color: #999;
  font-size: 12px;
}

.post-actions {
  margin-top: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.comments-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.comment-input {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}
.comment-input el-button {
  width:200px;

}
.comment-list {
  margin-top: 15px;
}

.comment-item {
  border-bottom: 1px solid #ddd;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.comment-user {
  font-weight: bold;
}

.comment-time {
  color: #999;
}

.reply-item {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.reply-author {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.reply-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.reply-nickname {
  font-weight: bold;
  margin-right: 10px;
}

.reply-date {
  color: #999;
  font-size: 12px;
}

.reply-actions {
  margin-top: 5px;
}

.reply-input {
  margin-top: 10px;
}
</style>